import type { NextPage } from 'next'
import Head from 'next/head'
import Link from 'next/link'

import styles from '../styles/Login.module.scss'
import { useEffect, useState } from 'react'

import router from 'next/router'

import { UserService } from '../services'
import { Dialog, Toast } from 'antd-mobile'
import { useRequest } from 'ahooks'
import { Warnicon, Winicon } from '../components/Icon'
import Cookies from 'js-cookie'

const Home: NextPage = () => {
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')

  const { data, run: goLogin } = useRequest(
    () => UserService.login(username, password),
    {
      manual: true,
      onSuccess: (res) => {
        if (res.stat === 'OK') {
          Toast.show({ content: <Winicon text='登录成功' /> })
          Cookies.set('user', res.user?.avatar, { expires: 7 })
          router.push('/')
        } else if (res.stat === 'ERR_LOGIN_FAILED') {
          Toast.show({ content: <Warnicon text={res.msg} /> })
        } else if (res.stat === 'ERR_NOT_FOUND') {
          Dialog.confirm({
            content: '账号不存在是否注册该账号',
            onConfirm: async () => {
              const res = await UserService.register(username, password)
              if (res.stat === 'OK') {
                Toast.show({ content: <Winicon text='注册成功自动登录' /> })
                goLogin()
              }
            }
          })
        }
        else {
          Toast.show({ content: <Warnicon text='请输入要求的用户名和密码' /> })
        }
      },
    });

  return (
    <div className="page">
      <Head>
        <title>登录页</title>
      </Head>
      <div className="wrap">
        <main className={styles.login}>
          <h3>民大二手书交易</h3>
          <div className={styles.inputwrap}>
            <input type="text" placeholder='账号(2-10位字符,推荐使用姓名)'
              value={username}
              onChange={(v) => setUsername(v.target.value)}
            />
            <i className="iconfont icon-shouji"></i>
          </div>
          <div className={styles.inputwrap}>
            <input type='password' placeholder='密码(6-18数字/字母/符号)'
              value={password}
              onChange={(v) => setPassword(v.target.value)}
            />
            <i className="iconfont icon-mima"></i>
          </div>
          <button onClick={goLogin} >注册/登录</button>
          <span onClick={() => { router.push('/') }}>游客模式</span>
        </main>
      </div>
    </div>
  )
}

export default Home
